import React, { useState, useEffect, useRef } from "react"; 
import http from '../utils/http'
import style from "./video.module.css";
import { useNavigate, useLocation } from "react-router-dom";

const AppPage = () => {
  const [isRecording, setIsRecording] = useState(false);
  const [recordedBlob, setRecordedBlob] = useState(null);
  const [file, setFile] = useState(null); // 用户选择的文件
  const [progress, setProgress] = useState(0); // 上传进度
  const [isUploading, setIsUploading] = useState(false); // 是否正在上传
  const [isPaused, setIsPaused] = useState(false); // 是否暂停
  const [videoUrl, setVideoUrl] = useState(null); // 上传完成后的视频链接
  const videoRef = useRef(null);
  const mediaRecorderRef = useRef(null);
  const circleRef = useRef(null);
  const animationStartTime = useRef(null);
  const animationFrameId = useRef(null);
  const autoStopTimer = useRef(null);
  const chunkIndexRef = useRef(0); // 当前上传的分片索引
  const xhrRef = useRef(null); // XMLHttpRequest 引用
  const navigate = useNavigate();
  const location = useLocation();

  const CHUNK_SIZE = 1024 * 1024; // 每个分片大小（1MB）

  // 初始化摄像头
  useEffect(() => {
    let stream;

    const initCamera = async () => {
      try {
        stream = await navigator.mediaDevices.getUserMedia({
          video: { facingMode: "user" }, // 前置摄像头
          audio: true,
        });
        videoRef.current.srcObject = stream;
      } catch (error) {
        console.error("摄像头访问失败:", error);
        alert("需要摄像头和麦克风权限才能使用此功能");
      }
    };

    initCamera();

    // 组件卸载或路由变化时清理媒体流
    return () => {
      if (stream) {
        stream.getTracks().forEach((track) => track.stop());
      }
    };
  }, []);

  // 监听路由变化，关闭摄像头
  useEffect(() => {
    return () => {
      if (videoRef.current?.srcObject) {
        const stream = videoRef.current.srcObject;
        stream.getTracks().forEach((track) => track.stop());
      }
    };
  }, [location]);

  // 动画处理
  const animateCircle = (timestamp) => {
    if (!animationStartTime.current) {
      animationStartTime.current = timestamp;
    }

    const progress = timestamp - animationStartTime.current;
    const percentage = Math.min(progress / 15000, 1);

    if (circleRef.current) {
      const circumference = 2 * Math.PI * 36; // r=36
      const offset = circumference * (1 - percentage);
      circleRef.current.style.strokeDashoffset = offset;
    }

    if (percentage < 1) {
      animationFrameId.current = requestAnimationFrame(animateCircle);
    }
  };

  // 开始录制
  const startRecording = () => {
    try {
      const stream = videoRef.current.srcObject;
      if (!stream) throw new Error("视频流不可用");

      // 初始化媒体录制
      mediaRecorderRef.current = new MediaRecorder(stream, {
        mimeType: "video/webm; codecs=vp9",
        videoBitsPerSecond: 2500000, // 2.5 Mbps
      });

      const chunks = [];
      mediaRecorderRef.current.ondataavailable = (e) =>
        e.data.size > 0 && chunks.push(e.data);
      mediaRecorderRef.current.onstop = async () => {
        const blob = new Blob(chunks, { type: "video/webm" });
        setFile(blob); // 将录制的视频保存为文件对象
        setRecordedBlob(URL.createObjectURL(blob)); // 显示预览
      };

      // 启动录制
      mediaRecorderRef.current.start();
      setIsRecording(true);
      animationStartTime.current = null;
      animationFrameId.current = requestAnimationFrame(animateCircle);

      // 自动停止定时器
      autoStopTimer.current = setTimeout(() => {
        if (mediaRecorderRef.current?.state === "recording") {
          mediaRecorderRef.current.stop();
        }
      }, 15000);
    } catch (error) {
      console.error("录制失败:", error);
      alert("视频录制功能不可用");
    }
  };

  // 停止录制
  const stopRecording = () => {
    if (mediaRecorderRef.current?.state === "recording") {
      mediaRecorderRef.current.stop();
      clearTimeout(autoStopTimer.current); // 清除自动停止定时器
      cancelAnimationFrame(animationFrameId.current);
      setIsRecording(false);
      animationStartTime.current = null; // 重置动画时间

      if (circleRef.current) {
        circleRef.current.style.strokeDashoffset = "226.195"; // 使用精确值
      }
    }
  };

  // 开始或恢复上传
  const startUpload = async () => {
    if (!file) return;

    setIsUploading(true);
    setIsPaused(false);

    while (chunkIndexRef.current * CHUNK_SIZE < file.size && !isPaused) {
      await uploadChunk();
    }

    if (!isPaused) {
      // 所有分片上传完成后，调用合并接口
      const fileName = `video-${Date.now()}.webm`;
      const totalChunks = Math.ceil(file.size / CHUNK_SIZE);

      try {
        const response = await http.post("/saveVideo", {
          fileName,
          totalChunks,
        });
        setVideoUrl(response.data.videoUrl); // 保存视频链接
        alert("上传完成！点击确定回首页");
        navigate("/"); // 跳转到视频列表页面
      } catch (error) {
        console.error("合并分片失败:", error);
        alert("上传失败，请重试");
      } finally {
        setIsUploading(false);
      }
    }
  };

  // 上传单个分片
  const uploadChunk = () => {
    return new Promise((resolve, reject) => {
      const start = chunkIndexRef.current * CHUNK_SIZE;
      const end = Math.min(start + CHUNK_SIZE, file.size);
      const chunk = file.slice(start, end);

      const formData = new FormData();
      formData.append("file", chunk);
      formData.append("chunkIndex", chunkIndexRef.current);
      formData.append("totalChunks", Math.ceil(file.size / CHUNK_SIZE));

      xhrRef.current = new XMLHttpRequest();

      xhrRef.current.upload.addEventListener("progress", (event) => {
        if (event.lengthComputable) {
          const chunkProgress =
            (chunkIndexRef.current * CHUNK_SIZE + event.loaded) / file.size;
          setProgress(chunkProgress * 100);
        }
      });

      xhrRef.current.onreadystatechange = () => {
        if (xhrRef.current.readyState === 4) {
          if (xhrRef.current.status === 200) {
            resolve();
          } else {
            reject(new Error("上传失败"));
          }
        }
      };

      xhrRef.current.open("POST", "http://localhost:3333/uploadChunk", true);
      xhrRef.current.send(formData);
    }).then(() => {
      chunkIndexRef.current++;
    });
  };

  // 暂停上传
  const pauseUpload = () => {
    if (xhrRef.current) {
      xhrRef.current.abort();
    }
    setIsPaused(true);
  };
  
  // 处理切换摄像头
  const handleSwitchCamera = () => {
    console.log('切换摄像头功能触发')
  };

  // 处理选择滤镜
  const handleSelectFilter = () => {
    console.log('选择滤镜功能触发')
  };

  // 处理定时拍摄
  const handleSetTimer = () => {
    console.log('定时拍摄功能触发')
  };
  return (
    <div className={style.container}>
      {/* 顶部提示信息 */}
      <div className={style.tipsBanner}>
        <p>点击下方按钮开始录制精彩视频（最长15秒）</p>
      </div>

      <video
        ref={videoRef}
        playsInline
        autoPlay
        muted
        className={style.fullscreenVideo}
      />

      <div className={style.controlsContainer}>
        <div className={style.recordButtonWrapper}>
          <svg className={style.progressRing} viewBox="0 0 80 80">
            <circle
              ref={circleRef}
              className={style.progressCircle}
              cx="40"
              cy="40"
              r="36"
              strokeDasharray="226.195" // 2πr = 2*3.1416*36 ≈ 226.195
              strokeDashoffset="226.195"
            />
          </svg>
          <button
            className={`${style.recordButton} ${isRecording ? style.recording : ""
              }`}
            onClick={isRecording ? stopRecording : startRecording}
          />
          <span className={style.recordButtonText}>
            {isRecording ? "点击停止" : "点击录制"}
          </span>
        </div>
      </div>

      {recordedBlob && (
        <div className={style.previewContainer}>
          <h3 className={style.previewTitle}>预览</h3>
          <video
            controls
            autoPlay
            loop
            src={recordedBlob}
            className={style["preview-video"]}
          />
          <div className={style.uploadControls}>
            <button
              className={style.uploadButton}
              onClick={startUpload}
              disabled={isUploading || !file}
            >
              {isUploading ? "上传中..." : "开始上传"}
            </button>
            <button
              className={style.pauseButton}
              onClick={pauseUpload}
              disabled={!isUploading || isPaused}
            >
              {isPaused ? "已暂停" : "暂停上传"}
            </button>
          </div>
          <div className={style.progressContainer}>
            <div className={style.progressBarWrapper}>
              <div
                className={style.progressBar}
                style={{ width: `${progress}%` }}
              ></div>
            </div>
            <span className={style.progressText}>{Math.round(progress)}%</span>
          </div>
          {isUploading && (
            <p className={style.uploadStatus}>
              {isPaused ? "上传已暂停，点击继续上传" : "正在上传视频，请稍候..."}
            </p>
          )}
        </div>
      )}
      // 添加拍摄功能按钮
      <div className={style.shootingButtons}>

        <button className={style.switchCameraButton} onClick={handleSwitchCamera}>切换摄像头</button>
        <button className={style.filterButton} onClick={handleSelectFilter}>选择滤镜</button>
        <button className={style.timerButton} onClick={handleSetTimer}>定时拍摄</button>
        <button style={{ position: 'absolute', top: '10px', left: '10px', background: 'none', border: 'none', color: 'white', fontSize: '24px', cursor: 'pointer' ,zIndex:1000}} onClick={() => navigate(-1)}>
          ✕
        </button>
      </div>
    </div>
  );
};

export default AppPage;